# -*- coding:utf-8 -*-
import urllib
import simplejson
import re
import os


def search_music(m_name,start_index=0,step=20):
    """
    : params tag_name : unicode
    : params start_index : start index for crawler

    http://music.baidu.com/search/song?key=%E6%88%91%E7%9A%84%E7%88%B1&start=0&size=20
    """
    tag_name = m_name
    the_url = "http://music.baidu.com/search/song?key=%s&start=%d&size=%d"%(tag_name.encode('utf-8'),start_index,step)
    html_str = urllib.urlopen(the_url).read()
    song_regex = "li data-songitem(\s|\S)*?/li"
    m_list = []
    for song_m in re.finditer(song_regex,html_str):
        song_str = html_str[song_m.start():song_m.end()]
        m_dic = {}

        # find song title
        title_regex = "song-title(\s|\S)*?/span"
        titlem = re.search(title_regex,song_str)
        if titlem:
            try:
                title_str = song_str[titlem.start():titlem.end()]
                title_id_index = title_str.index('song/')+5
                title_id_end = title_str.index('\"',title_id_index)
                title_name_index = title_str.index(' title')+8
                title_name_end = title_str.index('\"',title_name_index)
                title_id = title_str[title_id_index:title_id_end]
                title_name = title_str[title_name_index:title_name_end]
                m_dic['title'] = {
                        'id':title_id,
                        'name':title_name
                    }
            except Exception,e:
                #print title_str
                dono = 1
                continue
            #print m_dic

        # singers
        singers_regex = "author_list(\s|\S)*?/span"
        singers_m = re.search(singers_regex,song_str)
        if singers_m:
            singer_list = []
            singers_str = song_str[singers_m.start():singers_m.end()]
            singer_regex = "<a (\s|\S)*?</a>"
            for singerm in re.finditer(singer_regex,singers_str):
                singer_str = singers_str[singerm.start():singerm.end()]
                # find title and id here
                singer_id_index = singer_str.index('?id=')+4
                singer_id_end = singer_str.index('\"',singer_id_index)
                singer_name_index = singer_str.index('title')+7
                singer_name_end = singer_str.index('\"',singer_name_index)
                singer_id = singer_str[singer_id_index:singer_id_end]
                singer_name = singer_str[singer_name_index:singer_name_end]
                singer_list.append({'id':singer_id,'name':singer_name})
            m_dic['singers'] = singer_list



        # album info
        album_regex = "album-title(\s|\S)*?/span"
        albumm = re.search(album_regex,song_str)
        if albumm:
            try:
                album_str = song_str[albumm.start():albumm.end()]
                album_id_index = album_str.index('album/')+6
                album_id_end = album_str.index('\"',album_id_index)
                album_name_index = album_str.index(' title')+8
                album_name_end = album_str.index('\"',album_name_index)
                album_id = album_str[album_id_index:album_id_end]
                album_name = album_str[album_name_index:album_name_end]
                m_dic['album'] = {
                        'id':album_id,
                        'name':album_name
                    }
            except Exception,e:
                #print album_str
                #print e
                dono = 1
        m_list.append(m_dic)

    return m_list

good_tag_list = [u"浪漫",u"幸福",u"快乐",u"热恋",u"温馨",u"甜蜜",u"喜悦",u"美好",u"温暖",u"可爱",u"欢乐",u"幸福",u"开心",u"甜美",u"愉快",u"欢乐",u"喜悦",u"轻快"]
sad_tag_list = [u"孤单",u"忧郁",u"郁闷",u"惆怅",u"离别",u"孤独",u"悲伤",u"伤心",u"痛苦",u"苦涩",u"心痛",u"哀伤",u"疯狂",u"迷茫",u"伤感",u"思念",u"寂寞"]

if __name__ == "__main__":
    m_list = search_music(u"我的爱")
    for m in m_list:
        print m
    exit()
    """
    #http://music.baidu.com/search/tag?key=%E6%83%B3%E5%93%AD&start=60&size=20
    music_list = crawl_music_by_tag(u"想哭",60)
    for m in music_list:
        print 'title',m['title']
        print 'singers',m['singers']
        print 'album',m['album']
        #break
    exit()
    """

    for tag in good_tag_list+sad_tag_list:
        print tag
        for i in range(15):
            outpath = './data/%s-%d.json'%(tag,i)

            if os.path.isfile(outpath):
                continue
            
            print i
            try:
                music_list = crawl_music_by_tag(tag,i*20)
                outf = open(outpath,'w')
                print>>outf,simplejson.dumps(music_list)
                outf.close()
            except Exception,e:
                print e

            #break
        #break
